<template>
  <div style="height: calc(100% - 2px)">
    <div class="top-bar">
      <div class="right">
        <el-button type="primary" @click="addXm()">新增</el-button>
      </div>
    </div>
    <el-table
        :data="xmList"
        height="calc(100% - 28px)"
        stripe
        style="width: 100%">
      <el-table-column
          label="序号"
          type="index"
          width="50">
      </el-table-column>
      <el-table-column
          label="项目名称"
          show-overflow-tooltip>
        <template slot-scope="{row}">
          <el-link type="primary" @click="intoXm(row)">{{ row.xmmc }}</el-link>
        </template>
      </el-table-column>
      <el-table-column
          label="创建人员名称"
          prop="rymc"
          sortable
          width="150px">
      </el-table-column>
      <el-table-column
          label="创建时间"
          prop="cjsj"
          sortable
          width="180">
      </el-table-column>
      <el-table-column
          :width="isAdmin?310:230"
          label="操作">
        <template slot-scope="{row}">
          <el-popover
              placement="bottom"
              style="margin-right: 10px"
              title="请选择导出类型"
              trigger="click"
              width="370">
            <el-button type="primary" @click="dcGz(row,'2')">gzb规则包</el-button>
            <el-button type="primary" @click="dcGz(row,'1')">sql语句</el-button>
            <el-button type="primary" @click="dcGz(row,'0')">zip规则包（已弃用）</el-button>
            <el-link v-show="!isAdmin" slot="reference" type="primary">导出规则</el-link>
          </el-popover>
          <el-popconfirm
              confirm-button-text="继续导入"
              style="margin-right: 10px"
              title="导入规则包会清空以前的规则，且不可恢复，是否继续？"
              @confirm="drGz(row)">
            <el-link v-show="isAdmin||yhxx.dlbm!=='admin'&&yhxx.rybm===row.rybm" slot="reference" type="warning">导入规则
            </el-link>
          </el-popconfirm>
          <el-link type="primary" @click="addXm(row)">编辑</el-link>
          <el-link v-show="row.sfsc==='N'&&(yhxx.rybm===row.rybm||isAdmin)" style="margin-left: 15px"
                   type="danger"
                   @click="preDel(deleteXm,row,`即将删除【${row.xmmc}】,删除后不可恢复，是否继续？`)">删除
          </el-link>
          <el-link v-show="row.sfsc==='Y'" style="margin-left: 15px" type="primary" @click="undeleteXm(row)">恢复
          </el-link>
          <el-link v-show="isAdmin" style="margin-left: 15px" type="danger"
                   @click="preDel(qkxmgz,row,`即将删除【${row.xmmc}】的所有规则,删除后不可恢复，是否继续？`)">
            清空规则
          </el-link>
          <el-link v-show="row.sfsc==='Y'&&isAdmin" style="margin-left: 15px" type="danger"
                   @click="preDel(cdscXm,row,`即将删除【${row.xmmc}】,删除后不可恢复，是否继续？`)">彻底删除
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <xj-dialog :title="(xmForm.xmbm?'编辑':'新增')+'项目'"
               :visible="addXmDialogVisible"
               width="80%">
      <el-form :model="xmForm" label-width="70px">
        <el-form-item label="项目名称">
          <el-input v-model="xmForm.xmmc"></el-input>
        </el-form-item>
        <div style="display: flex;align-items: center">
          <div>
            <el-button type="primary" @click="addNewItem">添加项目配置项</el-button>
          </div>
          <div style="display: flex;align-items: center;margin-left: 20px">
            展示项
            <el-select v-model="xmForm.xmpz.zsbm" placeholder="请选择展示项" style="margin-left: 10px">
              <el-option
                  v-for="item in xmForm.xmpz.items"
                  :key="item.bm"
                  :label="item.mc"
                  :value="item.bm">
              </el-option>
            </el-select>
          </div>
          <div style="margin-left: 20px">
            核查字段必填
            <el-checkbox v-model="xmForm.xmpz.sfbthczd" style="margin-left: 10px"></el-checkbox>
          </div>
        </div>
        <el-table
            :data="xmForm.xmpz.items"
            stripe
            style="width: 100%">
          <el-table-column align="center" label="序号" type="index">
          </el-table-column>
          <!--<el-table-column align="center" label="展示" width="50">-->
          <!--  <template slot-scope="{row}">-->
          <!--    <el-checkbox :value="row.bm===xmForm.xmpz.zsbm" @change="handleZsChange($event,row)"></el-checkbox>-->
          <!--  </template>-->
          <!--</el-table-column>-->
          <el-table-column label="编码" width="100">
            <template slot-scope="{row}">
              <el-input v-model="row.bm"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="名称">
            <template slot-scope="{row}">
              <el-input v-model="row.mc"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="150">
            <template slot-scope="{row}">
              <el-select v-model="row.lx">
                <el-option
                    v-for="(v,k) in lxObj"
                    :key="k"
                    :label="v"
                    :value="k">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
              label="默认值"
              width="200">
            <template slot-scope="{row}">
              <div v-show="row.lx!=='input'">
                <el-select v-model="row.mrz">
                  <el-option
                      v-for="item in  row.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div v-show="row.lx==='input'">
                <el-input v-model="row.mrz"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="配置" type="expand">
            <template slot-scope="{row}">
              <div v-show="row.lx!=='input'">
                <el-form label-width="40px">
                  <div class="xmpz-box">
                    <div v-for="item in row.options"
                         style="display:grid;grid-template-columns: 160px 160px 1fr;">
                      <el-form-item label="名称">
                        <el-input v-model="item.label"></el-input>
                      </el-form-item>
                      <el-form-item label="值">
                        <el-input v-model="item.value"></el-input>
                      </el-form-item>
                      <div class="delete-btn" title="删除" @click="removeOptionItem(row.options,item)"></div>
                    </div>
                    <el-button class="add-btn" type="primary" @click="row.options.push({label:'',value:''})">添加
                    </el-button>
                  </div>
                </el-form>
              </div>
            </template>
          </el-table-column>
          <!--<el-table-column label="配置" width="400">-->
          <!--  <template slot-scope="{row}">-->
          <!--    <div v-show="row.lx!=='input'">-->
          <!--      <el-form label-width="40px">-->
          <!--        <div style="display: flex;flex-direction:column;align-items: center">-->
          <!--          <div style="flex: 1">-->

          <!--            <div v-for="item in row.options"-->
          <!--                 style="display:grid;grid-template-columns: 160px 160px 20px;">-->
          <!--              <el-form-item label="名称">-->
          <!--                <el-input v-model="item.label"></el-input>-->
          <!--              </el-form-item>-->
          <!--              <el-form-item label="值">-->
          <!--                <el-input v-model="item.value"></el-input>-->
          <!--              </el-form-item>-->
          <!--              <div class="delete-btn" title="删除" @click="removeOptionItem(row.options,item)"></div>-->
          <!--            </div>-->
          <!--          </div>-->
          <!--          <div class="add-btn-box" @click="row.options.push({label:'',value:''})">-->
          <!--            <div class="add-btn"></div>-->
          <!--          </div>-->
          <!--        </div>-->
          <!--      </el-form>-->
          <!--    </div>-->
          <!--  </template>-->
          <!--</el-table-column>-->
          <el-table-column align="center" label="操作" width="60px">
            <template slot-scope="{row}">
              <el-button type="danger" @click="removeItem(xmForm.xmpz.items,row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer">
        <el-button @click="handleAddXmBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleAddXmBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
    <xj-dialog :title="`SQL-${sqlTitle}`"
               :visible="!!sqlText" height="100%" width="calc(100% - 30vw)">
      <code-editor
          :value="sqlText"
          style="height: 99%">
      </code-editor>
      <div slot="footer">
        <el-button type="primary" @click="downloadSql">保存到本地</el-button>
        <el-button @click="sqlText=''">关闭</el-button>
      </div>
    </xj-dialog>

    <!--<xj-dialog title="编辑器测试"-->
    <!--           height="100%" width="calc(100% - 30vw)" visible>-->
    <!--  <code-editor-->
    <!--      :options="{language:'java'}"-->
    <!--      :value="sqlText"-->
    <!--      style="height: 99%">-->
    <!--  </code-editor>-->
    <!--</xj-dialog>-->
  </div>
</template>

<script>
import commonMixins from "@/mixins/commonMixins";
import XjDialog from "@/components/XjDialog";
import CodeEditor from "@/components/CodeEditor";
import storeUtil from "@/util/storeUtil";

export default {
  name: "Xmgl",
  components: { XjDialog, CodeEditor },
  mixins: [commonMixins],
  data () {
    return {
      lxObj: {
        'radio-button': '单选',
        'select': '下拉菜单',
        'input': '输入框',
      },
      xmList: [],
      xmForm: {
        xmbm: '',
        xmmc: '',
        xmpz: {
          zsbm: '',
          sfbthczd: false,
          items: []
        },
      },
      addXmDialogVisible: false,
      sqlTitle: '',
      sqlText: '',
    }
  },
  mounted () {
    this.queryXmList();
  },
  methods: {
    async queryXmList () {
      let xmList = await this.$api.queryXmListByRybm({ rybm: this.yhxx.rybm })
      this.xmList = xmList.map(xm => {
        return {
          ...xm,
          xmpz: JSON.parse(xm.xmpz || '{items:[]}')
        }
      })
    },
    handleZsChange (e, row) {
      if (e) {
        this.$set(this.xmForm.xmpz, "zsbm", row.bm)
      } else {
        this.$set(this.xmForm.xmpz, "zsbm", '')
      }
    },
    addNewItem () {
      let hasEmpty = this.xmForm.xmpz.items.some(item => !item.bm)
      if (hasEmpty) {
        return this.$message({
          message: `存在空的编码`,
          type: "error"
        })
      }
      this.xmForm.xmpz.items.push({
        mc: '',
        bm: '',
        mrz: '',
        lx: 'input',
        options: []
      })
    },
    async dcGz (xm, dclx) {
      try {
        let filePath = await this.$api.dcGz({ xmbm: xm.xmbm, dclx })
        let response = await this.$api.download({ filePath: filePath }, { responseType: 'blob' })
        this.sqlTitle = decodeURIComponent(response.headers['filename'])
        if (dclx === '1') {
          this.sqlText = await storeUtil.blob2String(response.data);
        } else {
          return storeUtil.downloadFileByBlob(response.data, this.sqlTitle)
        }
      } catch (e) {
        this.$message({ message: `下载失败：${e.message}`, type: "error" })
      }
    },
    downloadSql () {
      storeUtil.downloadFileByText(this.sqlText, this.sqlTitle);
    },
    async drGz (xm) {
      try {
        let file = await new Promise((resolve, reject) => {
          let timer = setTimeout(() => {
            return reject(new Error("选取文件超时"))
          }, 60 * 1000)
          let input = document.createElement("input")
          input.type = "file"
          input.accept = "application/x-zip-compressed,application/zip"
          input.onchange = async (e) => {
            if (timer) {
              clearTimeout(timer)
            }
            resolve(input.files[0])
          }
          input.click()
        })

        if (file.type !== "application/x-zip-compressed" && file.type !== "application/zip") {
          console.log("选择规则包类型：", file.type)
          throw new Error("选择的文件不是zip类型，请检查")
        }
        // 开始导入
        let formData = new FormData()
        formData.append("xmbm", xm.xmbm)
        formData.append("file", file)
        let res = await this.$api.drGz(formData, {}, { loadingText: '规则导入中，请稍后' })
        this.$message({ message: '导入成功', type: "success" })
      } catch (e) {
        this.$message({ message: e.message, type: "error" })
      }
    },
    intoXm (xm) {
      mySessionStorage.setItem("xm-item", xm)
      this.$router.push(`/xmsy`)
    },
    async addXm (xm) {
      if (!xm) {
        xm = {
          xmbm: '',
          xmmc: '',
          xmpz: { items: [], zsbm: '', sfbthczd: false }
        }
      }
      let xmForm = JSON.parse(JSON.stringify(xm))
      this.xmForm = { xmpz: { items: [] }, ...xmForm }
      this.xmForm.xmpz = { items: [], zsbm: '', sfbthczd: false, ...xmForm.xmpz }
      this.addXmDialogVisible = true
    },
    removeOptionItem (options, option) {
      let idx = options.findIndex(opt => opt.label === option.label)
      if (idx > -1) {
        options.splice(idx, 1)
      }
    },
    removeItem (items, pzItem) {
      let idx = items.findIndex(item => item.bm === pzItem.bm)
      if (idx > -1) {
        items.splice(idx, 1)
      }
    },
    async handleAddXmBtnClick (isConfirm) {
      if (isConfirm) {
        // 数据校验

        let xmpz = this.xmForm.xmpz
        for (let xmpzElement of xmpz.items) {
          if (!xmpzElement.mc) {
            return this.$message({
              message: `部分名称为空`,
              type: "error"
            })
          }
          if (!xmpzElement.bm) {
            return this.$message({
              message: `部分编码为空`,
              type: "error"
            })
          }
          if (xmpzElement.lx === 'radio-button' || xmpzElement.lx === 'select') {
            if (!xmpzElement.options.length) {
              return this.$message({
                message: `【${xmpzElement.mc}】的类型为【${this.lxObj[xmpzElement.lx]}】，配置不能为空`,
                type: "error"
              })
            }
            for (let option of xmpzElement.options) {
              if (!option.label) {
                return this.$message({
                  message: `【${xmpzElement.mc}】的部分配置名称为空`,
                  type: "error"
                })
              }
              if (!option.value) {
                return this.$message({
                  message: `【${xmpzElement.mc}】的部分配置值为空`,
                  type: "error"
                })
              }
            }
            if (xmpzElement.mrz) {
              let isOk = xmpzElement.options.some(item => item.value === xmpzElement.mrz)
              if (!isOk) {
                return this.$message({
                  message: `【${xmpzElement.mc}】的默认值【${this.lxObj[xmpzElement.lx]}】不正确，请检查！`,
                  type: "error"
                })
              }
            }
          }
        }

        // 进行保存
        try {
          if (this.xmForm.xmbm) {
            await this.$api.updateXm({
              xmbm: this.xmForm.xmbm,
              xmmc: this.xmForm.xmmc,
              xmpz: JSON.stringify(xmpz),
            })
          } else {
            await this.$api.addXm({
              xmmc: this.xmForm.xmmc,
              rybm: this.yhxx.rybm,
              rymc: this.yhxx.mc,
              xmpz: JSON.stringify(xmpz),
            })
          }
          this.queryXmList()
        } catch (e) {
          this.$message({ message: e.message, type: 'error' })
          return
        }
      }
      this.addXmDialogVisible = false
      this.xmForm = { xmbm: '', xmmc: '', xmpz: { items: [] } }
    },
    async cdscXm (xm) {
      await this.$api.cdscXm({ xmbm: xm.xmbm })
      this.$message({ message: "删除成功", type: 'success' })
      this.queryXmList()
    },
    async deleteXm (xm) {
      try {
        await this.$api.deleteXm({ xmbm: xm.xmbm })
        this.$message({ message: "删除成功", type: 'success' })
        this.queryXmList()
      } catch (e) {
        this.$message({ message: e.message, type: 'error' })
      }
    },
    async undeleteXm (xm) {
      await this.$api.undeleteXm({ xmbm: xm.xmbm })
      this.queryXmList()
    },
    async qkxmgz (xm) {
      try {
        await this.$api.qkxmgz({ xmbm: xm.xmbm })
        this.$message.success("操作成功")
      } catch (e) {
        this.$message.error(`清空失败：${e.message}`)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.delete-btn {
  background-image: url("~@/assets/svg/delete.svg");
  background-repeat: no-repeat;
  background-position: center;
  width: 28px;
  height: 28px;
  cursor: pointer;
}

::v-deep .xmpz-box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 370px);
  //align-items: center;
  //justify-items: center;

  > div:nth-child(2n) {
    //background-color: #cccccc;
  }

  .add-btn {
    //background-image: url("~@/assets/svg/add.svg");
    //background-repeat: no-repeat;
    //background-position: center;
    //background-size: 70%;
    //width: 28px;
    height: 28px;
    margin-bottom: 20px;
    width: calc(100% - 28px);
    //cursor: pointer;
    //background-color: #cccccc;
  }
}
</style>
